/**
 * 数据源列表页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Popconfirm,
  message,
  Tooltip,
  Modal,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  DatabaseOutlined,
  FileTextOutlined,
  FileExcelOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import {
  getDataSources,
  deleteDataSource,
  testConnection,
  previewData,
  type DataSourceItem,
  type DataPreviewResponse,
} from '@/services/dataSource';

const { Search } = Input;
const { Option } = Select;

const DataSourceList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<DataSourceItem[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewData, setPreviewData] = useState<DataPreviewResponse | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  // 获取数据源列表
  const fetchDataSources = async () => {
    setLoading(true);
    try {
      const response = await getDataSources({
        page: current,
        size: pageSize,
        search: searchText || undefined,
        type: typeFilter || undefined,
      });
      setDataSource(response.items);
      setTotal(response.total);
    } catch (error: any) {
      message.error(error.message || '获取数据源列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDataSources();
  }, [current, pageSize, searchText, typeFilter]);

  // 删除数据源
  const handleDelete = async (id: number) => {
    try {
      await deleteDataSource(id);
      message.success('删除成功');
      fetchDataSources();
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  // 测试连接
  const handleTestConnection = async (record: DataSourceItem) => {
    try {
      const result = await testConnection({
        type: record.type,
        config: record.config,
      });
      if (result.success) {
        message.success(result.message);
      } else {
        message.error(result.message);
      }
    } catch (error: any) {
      message.error(error.message || '连接测试失败');
    }
  };

  // 预览数据
  const handlePreviewData = async (record: DataSourceItem) => {
    setPreviewLoading(true);
    setPreviewVisible(true);
    try {
      const result = await previewData({
        data_source_id: record.id,
        limit: 10,
      });
      setPreviewData(result);
    } catch (error: any) {
      message.error(error.message || '数据预览失败');
      setPreviewVisible(false);
    } finally {
      setPreviewLoading(false);
    }
  };

  // 数据源类型图标和标签
  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'mysql':
        return <DatabaseOutlined style={{ color: '#1890ff' }} />;
      case 'csv':
        return <FileTextOutlined style={{ color: '#52c41a' }} />;
      case 'excel':
        return <FileExcelOutlined style={{ color: '#fa8c16' }} />;
      default:
        return <DatabaseOutlined />;
    }
  };

  const getTypeTag = (type: string) => {
    const configs = {
      mysql: { color: 'blue', text: 'MySQL' },
      csv: { color: 'green', text: 'CSV' },
      excel: { color: 'orange', text: 'Excel' },
    };
    const config = configs[type as keyof typeof configs] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns: ColumnsType<DataSourceItem> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          {getTypeIcon(record.type)}
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => getTypeTag(type),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text) => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="测试连接">
            <Button
              type="text"
              icon={<ApiOutlined />}
              onClick={() => handleTestConnection(record)}
            />
          </Tooltip>
          <Tooltip title="预览数据">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handlePreviewData(record)}
            />
          </Tooltip>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => history.push(`/datasources/detail/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => history.push(`/datasources/edit/${record.id}`)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个数据源吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '数据源管理',
        breadcrumb: {},
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Search
              placeholder="搜索数据源名称"
              allowClear
              style={{ width: 300 }}
              onSearch={setSearchText}
            />
            <Select
              placeholder="选择类型"
              allowClear
              style={{ width: 120 }}
              onChange={setTypeFilter}
            >
              <Option value="mysql">MySQL</Option>
              <Option value="csv">CSV</Option>
              <Option value="excel">Excel</Option>
            </Select>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => history.push('/datasources/create')}
            >
              新建数据源
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: setCurrent,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      {/* 数据预览弹窗 */}
      <Modal
        title="数据预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        {previewLoading ? (
          <div style={{ textAlign: 'center', padding: 40 }}>加载中...</div>
        ) : previewData ? (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Space>
                <span>总行数: {previewData.total_rows || '未知'}</span>
                <span>预览行数: {previewData.sample_rows}</span>
              </Space>
            </div>
            <Table
              columns={previewData.columns.map((col) => ({
                title: col,
                dataIndex: col,
                key: col,
                ellipsis: true,
              }))}
              dataSource={previewData.data.map((row, index) => {
                const obj: any = { key: index };
                previewData.columns.forEach((col, colIndex) => {
                  obj[col] = row[colIndex];
                });
                return obj;
              })}
              pagination={false}
              scroll={{ x: true, y: 400 }}
              size="small"
            />
          </div>
        ) : null}
      </Modal>
    </PageContainer>
  );
};

export default DataSourceList;
